package io.github.lee.jel.ui.main.home

import android.content.res.Configuration
import android.graphics.Color
import android.graphics.Typeface
import android.view.View
import android.widget.LinearLayout
import androidx.appcompat.widget.Toolbar
import androidx.core.content.res.ResourcesCompat
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.viewModels
import dagger.hilt.android.AndroidEntryPoint
import io.github.lee.core.ui.BaseFragment
import io.github.lee.core.ui.ba.gone
import io.github.lee.core.ui.ba.parentViewGroup
import io.github.lee.core.ui.databinding.ToolbarSimpleCenterTitleBinding
import io.github.lee.core.util.getColor
import io.github.lee.core.util.toPx
import io.github.lee.core.vm.err.ViewModelException
import io.github.lee.jel.R
import io.github.lee.jel.databinding.FragmentHomeBinding
import io.github.lee.jel.databinding.LayoutGlobalLoadingBinding
import io.github.lee.jel.databinding.LayoutHomeEmptyBinding
import io.github.lee.jel.databinding.LayoutHomeLatestBinding
import io.github.lee.jel.databinding.LayoutHomePlayingBinding
import io.github.lee.jel.databinding.LayoutHorizontalScrollItemBinding
import io.github.lee.jel.domain.Item
import io.github.lee.jel.global.session
import io.github.lee.jel.ui.item.detail.ItemDetailActivity
import io.github.lee.jel.ui.server.add.AddServerActivity
import kotlin.math.roundToInt

@AndroidEntryPoint
class HomeFragment : BaseFragment<FragmentHomeBinding, HomeVM>() {

    companion object {
        fun newInstance(): HomeFragment = HomeFragment()
    }

    //===Desc:=============================================================
    override fun onCreateViewModel(): HomeVM = viewModels<HomeVM>().value


    override fun onCreateToolbar(): Toolbar =
        ToolbarSimpleCenterTitleBinding.inflate(layoutInflater).also {
            it.bg = ResourcesCompat.getColor(resources, R.color.main_background_grey, null)
            it.titleColor = Color.TRANSPARENT
        }.toolbar

    override fun showEmpty(e: ViewModelException?) {
        super.showEmpty(e)
        toolbar?.parentViewGroup?.gone(true)
    }

    override fun showLoading(tip: String?) {
        super.showLoading(tip)
        toolbar?.parentViewGroup?.gone(true)
    }

    override fun showSuccess() {
        super.showSuccess()
        toolbar?.parentViewGroup?.gone(false)
    }

    override fun onCreateLoading(): ViewDataBinding =
        LayoutGlobalLoadingBinding.inflate(layoutInflater)
            .also {
                it.bg = getColor(R.color.main_background_grey)
            }

    override fun onCreateEmpty(): ViewDataBinding =
        LayoutHomeEmptyBinding.inflate(layoutInflater).also {
            it.vm = vm
        }


    override fun onCreateSuccess(): FragmentHomeBinding =
        FragmentHomeBinding.inflate(layoutInflater)

    //===Desc:=============================================================

    override fun onObserved() {
        super.onObserved()
        vm?.apply {
            addServerClickLiveData.observe(this@HomeFragment) {
                if (it) {
                    AddServerActivity.start(mContext)
                    addServerClickLiveData.postValue(false)
                }
            }

            homeLiveData.observe(this@HomeFragment) {
                vb?.srlRefresh?.isRefreshing = false

                val playing = it.playing
                val classify = it.classify
                vb?.llContent?.removeAllViews()
                val playingView = handPlayingView(playing)
                if (null != playingView) {
                    vb?.llContent?.addView(handPlayingView(playing))
                }

                classify?.forEach { c ->
                    val latestView = handleLatestView(c)
                    if (null != latestView) {
                        val params = LinearLayout.LayoutParams(
                            LinearLayout.LayoutParams.MATCH_PARENT,
                            LinearLayout.LayoutParams.WRAP_CONTENT
                        )
                        params.topMargin = 8.toPx(mContext)
                        vb?.llContent?.addView(latestView, params)
                    }
                }

                showSuccess()
            }

        }
    }

    override fun onSetViewListener() {
        super.onSetViewListener()
        vb?.srlRefresh?.setOnRefreshListener {
            val session = mContext.session
            if (null != session) {
                vm?.sync(session, false)
            } else {
                showEmpty()
            }
        }
    }

    override fun onSetViewData() {
        super.onSetViewData()

        val bg = getColor(R.color.main_background_grey)
        statusBarColor(bg, true, true)
        navigationBarColor(bg, true)

        vb?.llContent?.removeAllViews()
        vb?.srlRefresh?.setColorSchemeColors(getColor(R.color.main))


    }

    //===Desc:=============================================================

    private fun handleLatestView(classify: Classify?): View? {
        if (null == classify || classify.list.isEmpty()) {
            return null
        }

        val latest = LayoutHomeLatestBinding.inflate(layoutInflater)
            .apply { title = classify.title }
        val list = classify.list
        latest.llLatestList.removeAllViews()
        list.forEachIndexed { index, it ->
            val itemView = LayoutHorizontalScrollItemBinding.inflate(layoutInflater)
                .apply {
                    item = it
                    showPlay = false
                    radius = 4.toPx(mContext)
                    showProgressBar = false
                    ratio = 1.8F / 2.7F
                }
            itemView.root.setOnClickListener { _ ->
                ItemDetailActivity.start(mContext, it)
            }
            val width = resources.displayMetrics.widthPixels
            val density = resources.displayMetrics.density
            val widthDp = (width * 1.0F / density).roundToInt()
            val maxItemWidth = if (widthDp > 600) {
                width / 8
            } else {
                width * 1 / 4
            }
            val params = LinearLayout.LayoutParams(
                maxItemWidth,
                LinearLayout.LayoutParams.WRAP_CONTENT
            )
            if (index == 0) {
                params.marginStart = 16.toPx(mContext)
            } else if (index == list.size - 1) {
                params.marginEnd = 16.toPx(mContext)
            }

            latest.llLatestList.addView(itemView.root, params)
        }
        latest.llLatestList.gone(false)
        return latest.root
    }

    private fun handPlayingView(list: List<Item>?): View? {
        if (list.isNullOrEmpty()) {
            return null
        }

        val playingLayout = LayoutHomePlayingBinding.inflate(layoutInflater)
        playingLayout.llPlayingList.removeAllViews()
        list.forEachIndexed { index, it ->
            val itemView = LayoutHorizontalScrollItemBinding.inflate(layoutInflater)
                .apply {
                    item = it
                    showPlay = true
                    radius = 8.toPx(mContext)
                    showProgressBar = true
                    ratio = 6F / 3.5F
                }
            itemView.root.setOnClickListener { _ ->
                ItemDetailActivity.start(mContext, it)
            }
            val width = resources.displayMetrics.widthPixels
            val density = resources.displayMetrics.density
            val widthDp = (width * 1.0F / density).roundToInt()
            val maxItemWidth = if (widthDp > 600) {
                width / 3
            } else {
                width * 3 / 4
            }
            val params = LinearLayout.LayoutParams(
                maxItemWidth,
                LinearLayout.LayoutParams.WRAP_CONTENT
            )
            if (index == 0) {
                params.marginStart = 16.toPx(mContext)
            } else if (index == list.size - 1) {
                params.marginEnd = 16.toPx(mContext)
            }

            playingLayout.llPlayingList.addView(itemView.root, params)

        }
        playingLayout.llPlayingList.gone(false)
        return playingLayout.root
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        val showData = vm?.homeLiveData?.value
        if (null == showData) {
            showEmpty()
            return
        }

        val playing = vm?.homeLiveData?.value?.playing
        val classify = vm?.homeLiveData?.value?.classify
        vb?.llContent?.removeAllViews()
        val playingView = handPlayingView(playing)
        if (null != playingView) {
            vb?.llContent?.addView(handPlayingView(playing))
        }

        classify?.forEach { c ->
            val latestView = handleLatestView(c)
            if (null != latestView) {
                val params = LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
                )
                params.topMargin = 8.toPx(mContext)
                vb?.llContent?.addView(latestView, params)
            }
        }

        showSuccess()

    }

    private fun setFonts() {
        val typeface =
            Typeface.createFromAsset(activity?.assets, "fonts/AlimamaDongFangDaKai-Regular.ttf");

        try {
            val typefaceField = Typeface::class.java.getDeclaredField("MONOSPACE")
            typefaceField.isAccessible = true
            typefaceField.set(null, typeface)
        } catch (e: Exception) {
            e.printStackTrace()
        }


    }
}